<template>
  <div class="container">
    <div id="mars3dcontent"></div>
    <div class="layercontrol">
      <div class="item" style="display: flex">
        <div style="padding: 1vh">卫星地图</div>
        <el-switch
          style="padding: 1vh"
          size="large"
          v-model="imagemap"
          @change="switchImageLayer"
        />
      </div>
      <div class="item" style="display: flex">
        <div style="padding: 1vh">管网矢量地图</div>
        <el-switch
          style="padding: 1vh"
          size="large"
          v-model="pipemap"
          @change="switchPipLine"
        />
      </div>
    </div>
    <div class="tablecontainer" v-if="panelshow">
      <div class="tableForm">
        <div class="form">
          <div class="select">
            <div style="margin-left: 20px">流域：</div>
            <el-select
              v-model="basinvalue"
              placeholder="请选择..."
              size="large"
              style="width: 160px"
              @change="basinChange"
            >
              <el-option
                v-for="item in basinoptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <div>街道名称：</div>
            <el-input
              v-model="streetname"
              style="width: 160px"
              size="large"
              placeholder="请输入"
              @change="streetChange"
            />
            <div>道路名称：</div>
            <el-input
              v-model="roadname"
              style="width: 160px"
              size="large"
              placeholder="请输入"
              @change="roadChange"
            />
            <div>运维类型：</div>
            <el-select
              v-model="runtype"
              placeholder="请选择..."
              size="large"
              style="width: 160px"
              @change="runtypeChange"
            >
              <el-option
                v-for="item in runoptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
          <div class="bottomlist">
            <el-dropdown placement="bottom-start" @command="selectItem">
              <el-button color="#0000ff" :dark="isDark" :bg="false" size="large" plain
                >选择</el-button
              >
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="全选"
                    ><img
                      :src="selectall"
                      style="filter: grayscale(50%); padding-right: 8px"
                    />全选</el-dropdown-item
                  >
                  <el-dropdown-item command="多边形选择"
                    ><img
                      :src="selectpolygon"
                      style="filter: grayscale(50%); padding-right: 8px"
                    />多边形选择</el-dropdown-item
                  >
                  <el-dropdown-item command="点选"
                    ><img
                      :src="selectsingle"
                      style="filter: grayscale(50%); padding-right: 8px"
                    />点选</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-button
              color="#0000ff"
              :dark="isDark"
              style="margin-left: 12px"
              :bg="false"
              size="large"
              plain
              @click="clearSearch"
              >清空</el-button
            >
            <el-button color="#0000ff" :dark="isDark" size="large" @click="searchTable"
              >查询</el-button
            >
            <el-button color="#0000ff" :dark="isDark" size="large" @click="showTask"
              >处理</el-button
            >
            <div class="div-button" style="margin-left: 35px" @click="closePanel">
              <img :src="close" />
            </div>
          </div>
        </div>
        <div class="tableposition">
          <el-table
            :data="tableData"
            :cell-style="cellgradeStyle"
            :header-cell-style="headerStyle"
            style="width: 97%"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column property="basin" label="流域名称" width="120" />
            <el-table-column property="streetName" label="街道名称" />
            <el-table-column property="roadName" label="道路名称" />
            <el-table-column property="operateName" label="运维类型" />
            <el-table-column property="componentName" label="部件名称" />
            <el-table-column property="componentNo" label="部件编号" />
            <el-table-column
              property="defectName"
              label="缺陷名称"
              :show-overflow-tooltip="true"
            />
            <el-table-column property="patrolTime" label="巡查时间" />
            <el-table-column property="gradeName" label="紧急程度"> </el-table-column>
          </el-table>
          <div class="page">
            <div>
              <span style="font-size: 16px">显示{{ pagerow }}条消息 </span>
              <el-input-number
                v-model="currentPage"
                :min="1"
                :max="100"
                controls-position="right"
              />
              <span style="font-size: 16px">
                共 <span style="color: blue">{{ pagenumber }}</span> 条消息</span
              >
            </div>
            <el-pagination
              layout="prev, pager, next"
              :total="pagenumber"
              :page-size="pagerow"
              v-model:current-page="currentPage"
              :change="changePage(value)"
            />
          </div>
        </div>
      </div>
    </div>
    <handle v-if="taskPanel" @RefreshFee="closeHandle"></handle>
  </div>
</template>

<script setup>
import "mars3d-cesium/Build/Cesium/Widgets/widgets.css"; //依赖的cesium库本身css
import "mars3d/dist/mars3d.css";
import * as mars3d from "mars3d";
import * as turf from "@turf/turf";
import { nextTick, onMounted, onUnmounted, reactive, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { mapOptions } from "@/utils/mapOptions";
import { destroyMap, flytoView, transform } from "@/utils/Lmap";
import { Close } from "@element-plus/icons-vue";
import { patrolDataAnalysis, patrolProblemPoint } from "@/api/dataAnalysis/dataAnalysis";
import useAppStore from "@/store/modules/app";
// 组件导入
import handle from "./handle.vue";

// 图片导入
import selectall from "@/assets/trans/selectall.png";
import selectpolygon from "@/assets/trans/selectpolygon.png";
import selectsingle from "@/assets/trans/selectsingle.png";
import close from "@/assets/trans/close.png";

let map;
let imagemap = ref(false); // 影像地图
let pipemap = ref(false); // 管线地图
let pointLayer = new mars3d.layer.GraphicLayer({ zIndex: 1 }); // 图层
let selectLayer = new mars3d.layer.GraphicLayer({ zIndex: 2 }); // 图层
let drawLayer = new mars3d.layer.GraphicLayer(); // 绘制图层
let drawpolygon = [];

let isDark = false;
const store = useAppStore();

// 任务面板
let taskPanel = ref(false);
let panelshow = ref(true);

let pagerow = ref(4); // 列表显示行
let pagenumber = ref(0); // 行的总数量
let currentPage = ref(1); // 当前页数

let tableData = ref([]);
let totalData = [];
let selectData = [];

let basinoptions = [
  {
    value: "1",
    label: "跳墩河流域",
  },
  {
    value: "2",
    label: "肖家河流域",
  },
];

let runoptions = [
  {
    value: "1",
    label: "运行情况",
  },
  {
    value: "2",
    label: "设施情况",
  },
  {
    value: "3",
    label: "违法情况",
  },
];

let runtype = ref(""); // 运维类型绑定值
let basinvalue = ref(""); // 流域绑定值
let streetname = ref(""); // 街道绑定值
let roadname = ref(""); // 道路绑定值
let unnormalCompoment = ref([]); // 图上存在问题的点

let searchform = reactive({
  basin: basinvalue.value,
  operateType: runtype.value,
  roadName: roadname.value,
  streetName: streetname.value,
});

let tileLayer = new mars3d.layer.ArcGisLayer({
  url: "https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer",
  enablePickFeatures: false,
  // queryParameters: {
  //   mosaicRule: `{"where":"t='20180525'"}`,
  // },
});

const config = {
  url: "https://www.cqkckc.com/geoserver/hhgw/wms",
  layers: "hhgw:pipe_line",
  parameters: {
    VERSION: "1.1.1",
    transparent: true,
    format: "image/png",
  },
  crs: "EPSG:4326",
};
let wmsLayer = new mars3d.layer.WmsLayer(config);

watch(currentPage, (newval, oldval) => {
  tableData.value = JSON.parse(
    JSON.stringify(totalData.slice((newval - 1) * 4, (newval - 1) * 4 + 4))
  );
});

watch(unnormalCompoment, (newvalue, oldvalue) => {
  console.log(newvalue);
});

// 查询表格
function searchTable() {
  patrolDataAnalysis(searchform).then((res) => {
    console.log(res);
    if (res.code == 200) {
      pagenumber = res.data.length;
      totalData.length = 0;
      nextTick(() => {
        for (const eachdata of res.data) {
          totalData.push(eachdata);
        }
        tableData.value = JSON.parse(JSON.stringify(totalData.slice(0, pagerow.value)));
      });
    }
  });
}

// 获取列表
function getList() {
  patrolDataAnalysis({
    basin: "",
    operateType: "",
    roadName: "",
    streetName: "",
  }).then((res) => {
    pagenumber = res.data.length;
    nextTick(() => {
      for (const eachdata of res.data) {
        totalData.push(eachdata);
      }
      tableData.value = JSON.parse(JSON.stringify(totalData.slice(0, pagerow.value)));
    });
  });
}

// 设置表格的表头
function headerStyle({ row, column, rowIndex, columnIndex }) {
  return { color: "white", background: "#2A68F2" };
}

// 流域选择变化
function basinChange(value) {
  const select = basinoptions.find((item) => {
    if (item.value == value) {
      searchform.basin = item.label;
    }
  });
}

// 添加地图点要素
function addComponent(data, setcolor = "#ffff00", pixelSize = 10, layer = pointLayer) {
  let lng, lat;
  [lng, lat] = transform(data.coordinates.slice(0, 2));
  let attr = {
    attr: data,
  };
  const graphic = new mars3d.graphic.PointPrimitive({
    name: "贴地点",
    position: new mars3d.LngLatPoint(lng, lat),
    style: {
      color: setcolor,
      pixelSize: pixelSize,
      clampToGround: true,
      outlineWidth: 0,
      // 高亮时的样式（默认为鼠标移入，也可以指定type:'click'单击高亮），构造后也可以openHighlight、closeHighlight方法来手动调用
      highlight: {
        type: mars3d.EventType.click, // 默认为鼠标移入高亮，也可以指定click单击高亮
        pixelSize: 15,
        outlineColor: "#ff0000",
        outlineWidth: 2,
      },
    },
  });
  Object.assign(graphic, attr);
  const inthtml = `<table style="width: auto;color:black;border-radius: 5px;">
    <tr>
      <th scope="col" colspan="2" style="text-align:center;font-size:15px;background-color:#EDF4FF">信息</th>
    </tr>
    <tr>
      <td>部件ID：</td>
      <td>${data.componentNo}</td>
    </tr>
    <tr>
      <td>部件类型：</td>
      <td>${data.type == "1" ? "管点" : "管线"}</td>
    </tr>
  </table>`;
  graphic.bindPopup(inthtml);
  layer.addGraphic(graphic);
}

// 设置table单元格样式
function cellgradeStyle({ row, columnIndex }) {
  if (row.gradeName == "紧急" && columnIndex == 9) {
    return { color: "red" };
  }
  if (row.gradeName == "高" && columnIndex == 9) {
    return { color: "#DD966D" };
  }
  if (row.gradeName == "中" && columnIndex == 9) {
    return { color: "blue" };
  }
  if (row.gradeName == "低" && columnIndex == 9) {
    return { color: "green" };
  }
}

function changePage() {
  console.log(currentPage.value);
}

// 清空按钮
function clearSearch() {
  runtype.value = "";
  basinvalue.value = "";
  streetname.value = "";
  roadname.value = "";
  selectData = [];
  totalData = [];
  drawpolygon = [];
  selectLayer.clear(true);
  drawLayer.clear(true);
  pointLayer.off(mars3d.EventType.dblClick);
  getList();
}

function runtypeChange(value) {
  searchform.operateType = value;
}

function streetChange() {
  searchform.streetName = streetname;
}

function roadChange() {
  searchform.roadName = roadname;
}

function showInMap() {
  for (const eachdata of unnormalCompoment.value) {
    addComponent(eachdata, "#ff0000");
  }
}

function switchImageLayer() {
  if (imagemap.value) {
    map.addLayer(tileLayer);
  } else {
    map.removeLayer(tileLayer);
  }
}

function switchPipLine() {
  if (pipemap.value) {
    map.addLayer(wmsLayer);
  } else {
    map.removeLayer(wmsLayer);
  }
}

async function getProblemPoint() {
  await patrolProblemPoint().then((res) => {
    if (res.code == 200) {
      for (const eachdata of res.data.features) {
        let temp = {};
        temp.type = eachdata.properties.type;
        temp.componentId = eachdata.properties.componentId;
        temp.componentNo = eachdata.properties.componentNo;
        temp.coordinates = eachdata.geometry.coordinates;
        temp.select = "0";
        unnormalCompoment.value.push(temp);
      }
    }
  });
}

// 绘制
async function drawPolygon() {
  const graphic = await drawLayer.startDraw({
    type: "polygon",
    style: {
      color: "#ffff00",
      opacity: 0.5,
      outline: true,
      outlineColor: "#ff0000",
      outlineWidth: 2.0,
      clampToGround: true,
    },
  });
  drawpolygon.push(graphic.coordinates);
  console.log("完成了draw标绘", graphic);
}

// 根据id type 获取对应的列表数据
function getDataFromSelect() {
  tableData.value.length = 0;
  let filterdata = [];
  for (const eachdata of selectData) {
    filterdata.push(
      totalData.filter((item) => {
        if (item.componentId == eachdata.componentId && item.type == eachdata.type) {
          return item;
        }
      })
    );
  }
  totalData = filterdata.flat();
  nextTick(() => {
    pagenumber = totalData.length;
    currentPage.value = 1;
    tableData.value = totalData.slice(0, 4);
  });
}

async function checkDrawPolygon() {
  await drawPolygon();
  await ElMessageBox.confirm("是否继续选取区域?", "info", {
    confirmButtonText: "是",
    cancelButtonText: "否",
    type: "info",
  })
    .then(() => {
      return checkDrawPolygon();
    })
    .catch(() => {
      ElMessage({
        type: "success",
        message: "绘制完成",
      });
    });
}

// 根据多边形点创建polygon对象
function createPolygonObject() {
  let polygon = [];
  for (const eachdata of drawpolygon) {
    let data = [];
    eachdata.forEach((element) => {
      data.push(element);
    });
    data.push(eachdata[0]);
    polygon.push(turf.polygon([data]));
  }
  return polygon;
}

// 判断点是否在多边形内部
function checkPointInPolygon() {
  let polygons = createPolygonObject();
  for (const eachdata of unnormalCompoment.value) {
    let lng, lat;
    [lng, lat] = transform(eachdata.coordinates.slice(0, 2));
    for (const polygon of polygons) {
      let point = turf.point([lng, lat]);
      if (turf.booleanWithin(point, polygon)) {
        addComponent(eachdata, "#00ffff", 12, selectLayer);
        selectData.push(eachdata);
      }
    }
  }
}

// 重置totaldata
async function resetTotalData() {
  totalData = [];
  await patrolDataAnalysis({
    basin: "",
    operateType: "",
    roadName: "",
    streetName: "",
  }).then((res) => {
    if (res.code == 200) {
      for (const eachdata of res.data) {
        totalData.push(eachdata);
      }
    }
  });
}

// 判断数据是否在list中
function checkInSelect(point) {
  let boolinlist = false;
  selectData.filter((item) => {
    if (item.componentId == point.componentId && item.type == point.type) {
      boolinlist = true;
    }
  });
  return boolinlist;
}

// 选择绘制条件
async function selectItem(command) {
  if (command == "全选") {
    clearSearch();
    for (const eachdata of unnormalCompoment.value) {
      addComponent(eachdata, "#00ffff", 12, selectLayer);
      selectData.push(eachdata);
    }
    getDataFromSelect();
  }
  if (command == "多边形选择") {
    clearSearch();
    await checkDrawPolygon();
    checkPointInPolygon();
    getDataFromSelect();
  }
  if (command == "点选") {
    clearSearch();
    pointLayer.on(mars3d.EventType.dblClick, async function (event) {
      if ("graphic" in event && "attr" in event.graphic) {
        await resetTotalData();
        let selectpoint = event.graphic.attr;
        if (!checkInSelect(selectpoint)) {
          addComponent(selectpoint, "#00ffff", 18, selectLayer);
          selectData.push(event.graphic.attr);
          getDataFromSelect();
        }
      }
    });
  }
}

// 任务面板控制
function showTask() {
  taskPanel.value = true;
}

function closeHandle() {
  taskPanel.value = false;
}

const sideClick = (data) => {
  if (data.index == "/dataAnalysis/tranAnalysis") panelshow.value = true;
};
store.changeSide(sideClick);

// 关闭主页面表单
function closePanel() {
  panelshow.value = false;
}
// 获取列表当前
getList();
// 获取存在问题的管线、点

onMounted(async () => {
  map = new mars3d.Map("mars3dcontent", mapOptions);
  map.addLayer(pointLayer);
  map.addLayer(selectLayer);
  map.addLayer(drawLayer);
  await getProblemPoint();
  showInMap();
});

onUnmounted(() => {
  destroyMap(map);
});

// 获取数据
</script>

<style scoped>
.container {
  width: 100%;
  height: 100%;
  background-color: antiquewhite;
}

.layercontrol {
  position: fixed;
  top: 10vh;
  right: 10vh;
  width: 20vh;
  height: 10vh;
  border-radius: 1vh;
  background-color: white;
  z-index: 99;
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
  align-items: flex-start;
}

.item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

#mars3dcontent {
  width: 100%;
  height: 100%;
}

.tablecontainer {
  position: absolute;
  display: flex;
  justify-content: center;
  align-items: center;
  bottom: 0px;
  width: 100%;
  height: 40%;
  z-index: 99;
}

.el-input-number {
  width: 70px;
  text-align: left;
}

.el-input-number :deep(.el-input__wrapper) {
  padding-right: 0px;
  padding-left: 0px;
}

.el-input-number :deep(.el-input__inner) {
  text-align: left;
  text-indent: 5px;
}

.tableForm {
  width: 90%;
  height: 95%;
  background-color: white;
  border-radius: 1vh;
  z-index: 99;
}

.form {
  margin-top: 20px;
  display: flex;
  height: 10%;
}

.tableposition {
  margin-top: 30px;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  flex-direction: column;
}

.page {
  margin-top: 15px;
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0px 30px;
}
.select {
  display: flex;
  width: 70%;
  flex-wrap: nowrap;
  justify-content: space-evenly;
  align-items: center;
}

.bottomlist {
  display: flex;
  width: 30%;
  flex-wrap: nowrap;
  justify-content: space-evenly;
  align-items: center;
}

/* Pop关闭按钮 */
.container :deep(.closeButton) {
  color: black;
}
.container :deep(.mars3d-popup-content) {
  margin: 0px;
  border-radius: 5px;
}
.container :deep(.mars3d-popup-background) {
  border-radius: 10px;
}

.el-table th {
  background-color: antiquewhite;
}

.el-dropdown-item {
  display: flex;
}
.div-button {
  cursor: pointer;
}
</style>
